package com.foodapp.back.controller;

import com.foodapp.back.common.Result;
import com.foodapp.back.dto.LoginDTO;
import com.foodapp.back.dto.RegisterDTO;
import com.foodapp.back.service.UserService;
import com.foodapp.back.vo.UserVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody @Valid LoginDTO loginDTO) {
        Map<String, Object> result = userService.login(loginDTO);
        return Result.success(result);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody @Valid RegisterDTO registerDTO) {
        boolean result = userService.register(registerDTO);
        return Result.success(result);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<UserVO> getUserInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        UserVO userVO = userService.getUserInfo(userId);
        return Result.success(userVO);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<Boolean> updateUserInfo(HttpServletRequest request, @RequestBody UserVO userVO) {
        Long userId = (Long) request.getAttribute("userId");
        boolean result = userService.updateUserInfo(userId, userVO);
        return Result.success(result);
    }
}
